require_dependency 'map_utils'

class EcasesController < ApplicationController

  include MapUtils
  
  uses_tiny_mce :only => [:show, :teaching_notes]

  before_filter :set_countries_and_timeunits, :only => [:create, :update , :new , :edit]
  before_filter :set_ecase, :only => [:show, :edit ,:destroy, :update, :set_about_authors, 
    :set_description , :change_map_location, :teaching_notes, :set_teaching_notes]
  before_filter :set_ecase_to_save_region, :only => [:save_region]
  before_filter :authorize_author, :only => [:new, :create]
  before_filter :authorize_teacher, :only => [:teaching_notes]
  before_filter :authorize_ecase_owner, :only => [:edit, :update, :set_description, 
    :save_region, :set_about_authors, :change_map_location, :destroy,:set_teaching_notes]

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
    :redirect_to => {:action => :list }

  def index
    list
    render :action => :list
  end

  #generates list of A-Z ecases
  def list
    ecases = Ecase.find(:all, :order => "title ASC")
    notletters_ecases = Array.new
    @ecases = Array.new
    ecases.each do |e|
      if e.title[0,1].index(/[[a-zA-Z]/).nil? 
        notletters_ecases << e 
      else
        @ecases << e 
      end
    end 
    @ecases = @ecases + notletters_ecases
    set_list_map
  end

  #shows ecase page
  def show
    set_editing_layout
    pre_set_map_extended
    @slideshow = @ecase.slideshow
    if @slideshow
      @slideshow_xml = url_for(:controller => "slideshows", :action => :generate_xml, :id => @slideshow.id)
    end
    @comments_size = @ecase.comments.size.to_s
    @comments = @ecase.last_comments
    if params[:editor_action_id]   #checks tine_mce editor activity
      @editor_place = params[:editor_action_id]
      @editor_content = @ecase.send(@editor_place)
    end
    @commentable = @ref = @ecase
    @selected_tab = :ecase
    @opened_nodes = get_opened_nodes_for_ecase(@ecase.id)
  end

  def set_opened_nodes_for_ecase
    ecase_id = params[:id].to_i
    node = params[:node]
    opened = (params[:opened] == "true")

    get_opened_nodes[ecase_id].send(opened ? :push : :delete, node)
  end

  def get_opened_nodes_for_ecase(ecase_id_)
    get_opened_nodes[ecase_id_] ||= []
  end

  def get_opened_nodes
    session[:opened_nodes] ||= {}
  end

  #generates form for adding ecase
  def new
    @ecase = Ecase.new
  end

  #validate and create ecase
  def create
    y = params[:ecase_date][:year]
    m = params[:ecase_date][:month]
    d = params[:ecase_date][:day]
    @ecase = Ecase.new(params[:ecase])
    @ecase.author_id = get_session_user.id
    @ecase.date = datetime_str(y,m,d,0,0,0)
    if DateTime.valid_civil?(y.to_i,m.to_i,d.to_i)
      if @ecase.save
       flash[:notice] = "Case was successfully created."
       redirect_to :action => :change_map_location, :id => @ecase and return
      else
        render :action => :new
      end
    else
       set_flash_info( FlashInfo.get_error("Please enter correct date."))
       render :action => :new
    end
  end

  def save_region
    ecase_region = @ecase.ecase_region 
    if ecase_region
      @region = ecase_region
      @region.update_attributes(params[:region])
    else
      @region = EcaseRegion.new(params[:region])
      @region.save
    end
  end
 
  #generates form for editing ecase
  def edit
    @ecase_date = @ecase.date_time
    @selected_tab = :ecase
  end
  
  def update
    y = params[:ecase_date][:year]
    m = params[:ecase_date][:month]
    d = params[:ecase_date][:day]
    params[:ecase][:date] = datetime_str(y,m,d,0,0,0)
    if DateTime.valid_civil?(y.to_i,m.to_i,d.to_i)
      if @ecase.update_attributes(params[:ecase])
       flash[:notice] = "Case was successfully updated."
       redirect_to :action => :show, :id => @ecase and return
      else
        @selected_tab = "ecase"
        render :action => :edit
      end
    else
       set_flash_info(FlashInfo.get_error("Please enter correct date."))
       @selected_tab = :ecase
       render :action => :edit
    end
  end

  def destroy
    if !@ecase.slideshow.nil?
       @ecase.slideshow.destroy
    end
    @ecase.destroy
    redirect_to :action => :list
  end

  def set_about_authors
    if !@ecase.update_attribute("about_authors", params[:editor_content])
      flash[:notice] = 'About Authors text was not updated.'
    end
    redirect_to :action => :show, :id => params[:id]
  end 

  def set_description
    if !@ecase.update_attribute("description", params[:editor_content])
      flash[:notice] = 'Overview text was not updated.'
    end
    redirect_to :action => :show, :id => params[:id]
  end 

  def change_map_location
    @selected_tab = :ecase
    set_map(@ecase.ecase_region)
  end

  def teaching_notes
   set_editing_layout
   @selected_tab = :teaching_notes
   if params[:editor_action_id]   #checks tine_mce editor activity
      @editor_place = params[:editor_action_id]
      @editor_content = @ecase.send(@editor_place)
      @editor_width = "740px"
      @ref = @ecase
    end
  end
  
  def set_teaching_notes
    if !@ecase.update_attribute("teaching_notes", params[:editor_content])
      flash[:notice] = 'Teaching Notes text was not updated.'
    end
    redirect_to :action => 'teaching_notes', :id=> params[:id]
  end  
  
  private
  
  def set_countries_and_timeunits
    @countries = Country.find_all.collect {|p| [ p.name, p.id ] }
    @timeunits = Timeunit.find_all.collect {|p| [ p.name, p.id ] }
  end

  #sets edited ecase 
  def set_ecase_to_save_region
    @ecase = Ecase.find(params[:region][:ecase_id])
    if @ecase.nil?
       redirect_to :action => :list and return
    end
  end

  def set_ecase
    @ecase = Ecase.find(params[:id])
    if @ecase.nil?
       redirect_to :action => :list and return
    end
  end

  def pre_set_map_extended
     @ecase_region = @region = @ecase.ecase_region
     set_map_extended
  end
  # filter before "edit" and "update" actions
  # authorizes user to be admin or author and owner of given ecase
  # this allows to perform several actions
  def authorize_ecase_owner
    return false unless authorize_author

    authorized = admin_authorized? || (get_session_user.id == Ecase.find(@ecase.id).author_id) 

    unless authorized
      on_not_authorized("Please login as author of this ecase.")
    end

    authorized
  end
end
